<?php
include 'config.php';
?>
<!DOCTYPE html>  
<html lang="en">  
    <head>  
        <meta charset="utf-8">  
        <meta name="viewport" content="initial-scale=1.0">
        <title>Lista zakupów</title>  
        <link rel="stylesheet" href="style.css">  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script src="script.js"></script>  
    </head>  
    <body>  
        <?php
        $lista = file_get_contents('list');
        $lista = explode("\n", $lista);
        sort($lista);
        $lista2 = array();
        foreach ($lista as $value) {
            $tmp = explode(':', $value);

            $lista2[$tmp[1]] = $tmp[0];
        }
        asort($lista2);
        ?>
        <h1>Lista zakupów</h1>
        <?php
        /*
         * Part to send list to email
         */
        if (!empty($_POST)) {
            $message = '';
            foreach ($_POST as $key => $value) {
                if ($value) {
                    if ($key == 'extra')
                        $message .= "Extra: \n$value\n";
                    else
                        $message .= "$key x $value\n";
                }
            }
//            print_r($message);
            $headers = 'Reply-To: ' . REPLAY_EMAIL . "\r\n";
            $re = mail(LIST_EMAIL, 'Lista zakupów', $message, $headers);
            if ($re) {
                echo '<script>
                    $().ready(function(){
                        alert("Wiadomość poprawnie wysłana\nLista produktów:\n' . str_replace("\n", '\n', $message) . '")
                    });
                    </script>';
            }
            else
                echo '<script>
                     $().ready(function(){
                        alert("Wiadomość nie wysłana.")
                     });
                     </script>';
        }
        ?>
        <form method="post" >
            <table>
                <tbody>
                    <?php
                    foreach ($lista2 as $key => $value) {
                        echo '<tr>';
                        echo '<td>' . $key . '</td>';
                        echo "<td><input type='button' class='dodaj' value='Dodaj'/>";
                        echo "<input type='button' class='usun' value='Usuń'/>";
                        echo '<input type="text" name="' . $key . '" value="0"/></td>';
                        echo '</tr>';
                    }
                    ?>
                </tbody>
            </table>
            <h3>Dodatkowe produkty:</h3>
            <textarea name="extra"></textarea>
            <input type="submit" value="Wyślij"/>
        </form>
        <ul>
        </ul>
    </body>  
</html>  
